<template>
  <div class="prompt-detail-container">
    <a-spin :spinning="loading">
      <div v-if="prompt" class="prompt-content">
        <div class="prompt-header">
          <a-page-header
            :title="prompt.title"
            @back="router.push('/prompts')"
          >
            <template #tags>
              <a-tag v-for="tag in prompt.tags" :key="tag.id" color="blue">
                {{ tag.name }}
              </a-tag>
            </template>
            <template #extra>
              <a-space>
                <a-button v-if="isOwner" @click="router.push(`/prompts/${promptId}/edit`)">
                  <template #icon><EditOutlined /></template>
                  编辑
                </a-button>
                <a-button @click="handleCopy">
                  <template #icon><CopyOutlined /></template>
                  复制
                </a-button>
              </a-space>
            </template>
          </a-page-header>
        </div>

        <div class="prompt-meta">
          <div class="prompt-info">
            <span><UserOutlined /> {{ prompt.user.username }}</span>
            <span><ClockCircleOutlined /> 更新于 {{ formatDate(prompt.updated_at) }}</span>
            <span><EyeOutlined /> {{ prompt.view_count }} 次浏览</span>
          </div>
          <div class="prompt-model">
            <a-tag color="green">{{ prompt.ai_model.name }}</a-tag>
          </div>
        </div>

        <a-divider />

        <div class="prompt-description">
          <h3>描述</h3>
          <p>{{ prompt.description }}</p>
        </div>

        <div class="prompt-content-section">
          <h3>提示词内容</h3>
          <a-card class="prompt-content-card">
            <div class="prompt-actions">
              <a-button type="text" @click="copyContent">
                <template #icon><CopyOutlined /></template>
                复制内容
              </a-button>
            </div>
            <div class="prompt-text">{{ prompt.content }}</div>
          </a-card>
        </div>

        <div v-if="prompt.versions && prompt.versions.length > 0" class="prompt-versions">
          <h3>历史版本</h3>
          <a-collapse>
            <a-collapse-panel 
              v-for="(version, index) in prompt.versions" 
              :key="version.id" 
              :header="`版本 ${prompt.versions.length - index}: ${formatDate(version.created_at)}`"
            >
              <div class="version-content">
                <p>{{ version.content }}</p>
                <div class="version-actions">
                  <a-button size="small" @click="copyVersionContent(version.content)">
                    <template #icon><CopyOutlined /></template>
                    复制此版本
                  </a-button>
                </div>
              </div>
            </a-collapse-panel>
          </a-collapse>
        </div>
      </div>
      <a-empty v-else-if="!loading" description="提示词不存在或已被删除" />
    </a-spin>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { 
  EditOutlined, CopyOutlined, UserOutlined,
  ClockCircleOutlined, EyeOutlined
} from '@ant-design/icons-vue';
import { usePromptStore } from '../store/prompt';
import { useAuthStore } from '../store/auth';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';

// 定义类型接口


export default {
  name: 'PromptDetail',
  components: {
    EditOutlined,
    CopyOutlined,
    UserOutlined,
    ClockCircleOutlined,
    EyeOutlined
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const promptStore = usePromptStore();
    const authStore = useAuthStore();
    
    const promptId = ref(route.params.id);
    const prompt = ref(null);
    const loading = ref(true);
    
    const currentUser = computed(() => authStore.user);
    const isOwner = computed(() => {
      return currentUser.value && 
             prompt.value && 
             prompt.value.user.id === currentUser.value.id;
    });
    
    const loadPromptDetail = async () => {
      loading.value = true;
      try {
        const data = await promptStore.fetchPromptDetail(promptId.value);
        prompt.value = data;
      } catch (error) {
        message.error('获取提示词详情失败');
        console.error(error);
      } finally {
        loading.value = false;
      }
    };
    
    const handleCopy = async () => {
      try {
        const newPrompt = await promptStore.copyExistingPrompt(promptId.value);
        message.success('提示词复制成功');
        router.push(`/prompts/${newPrompt.id}`);
      } catch (error) {
        message.error('复制提示词失败');
        console.error(error);
      }
    };
    
    const copyContent = () => {
      if (!prompt.value) return;
      
      navigator.clipboard.writeText(prompt.value.content)
        .then(() => {
          message.success('提示词内容已复制到剪贴板');
        })
        .catch(() => {
          message.error('复制失败，请手动复制');
        });
    };
    
    const copyVersionContent = (content: string) => {
      navigator.clipboard.writeText(content)
        .then(() => {
          message.success('版本内容已复制到剪贴板');
        })
        .catch(() => {
          message.error('复制失败，请手动复制');
        });
    };
    
    const formatDate = (dateString: string) => {
      try {
        return formatDistanceToNow(new Date(dateString), { 
          addSuffix: true,
          locale: zhCN
        });
      } catch (e) {
        return dateString;
      }
    };
    
    onMounted(() => {
      loadPromptDetail();
    });
    
    return {
      router,
      promptId,
      prompt,
      loading,
      isOwner,
      handleCopy,
      copyContent,
      copyVersionContent,
      formatDate
    };
  }
};
</script>

<style scoped>
.prompt-detail-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.prompt-content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 1rem;
}

.prompt-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
}

.prompt-info {
  display: flex;
  gap: 1.5rem;
  color: rgba(0, 0, 0, 0.45);
}

.prompt-description {
  margin-bottom: 2rem;
}

.prompt-description h3 {
  margin-bottom: 0.5rem;
  font-size: 1.2rem;
}

.prompt-content-section {
  margin-bottom: 2rem;
}

.prompt-content-section h3 {
  margin-bottom: 0.5rem;
  font-size: 1.2rem;
}

.prompt-content-card {
  position: relative;
}

.prompt-actions {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
}

.prompt-text {
  white-space: pre-wrap;
  font-family: monospace;
  background-color: #f5f5f5;
  padding: 1rem;
  border-radius: 4px;
  margin-top: 1rem;
}

.prompt-versions {
  margin-top: 2rem;
}

.prompt-versions h3 {
  margin-bottom: 0.5rem;
  font-size: 1.2rem;
}

.version-content {
  white-space: pre-wrap;
  font-family: monospace;
}

.version-actions {
  margin-top: 1rem;
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .prompt-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  
  .prompt-info {
    flex-direction: column;
    gap: 0.5rem;
  }
}
</style>